<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="false">
        <template v-slot:after>
          <el-button
            size="mini"
            type="primary"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="onExcelExport"
          >导出</el-button>
          <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>

      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employees">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <img
                v-imgError="require('@/assets/common/bigUserHeader.png')"
                class="staffPhoto"
                :src="row.staffPhoto"
                @click="onClickAvatar(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" sortable>
            <template v-slot="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职时间" sortable>
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable>
            <template v-slot="scope">
              {{ scope.row.enableState ? "可用" : "不可用" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                :disabled="checkPermission(points.pointUserUpdate)"
                @click="$router.push('/employees/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small" :disabled="checkPermission(points.pointUserSetJob)">调岗</el-button>
              <el-button type="text" size="small" :disabled="checkPermission(points.pointUserLeave)">离职</el-button>
              <el-button type="text" size="small" @click="onClickRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                :disabled="checkPermission(points.pointUserDelete)"
                @click="onClickDel(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :page-size="tablePage.size"
            :total="total"
            layout="total, prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog :visible.sync="visibleQRCode">
      <canvas id="qrcode" />
    </el-dialog>

    <!-- 角色分配 -->
    <SetRoleDialog :set-role-dialog.sync="setRoleDialog" :employees-id="employeesId" />

    <AddEmployees :show-dialog.sync="showDialog" />
  </div>
</template>

<script>
import permissionMixins from '@/mixins/permission'
import SetRoleDialog from './components/SetRoleDialog.vue'
import { formatDate_day } from '@/utils'
import { formatHireType } from '@/filters'
import AddEmployees from './components/AddEmployees'
import { getEmployeesList, delEmployee } from '@/api/employees'
import QRCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployees,
    SetRoleDialog
  },
  // 混入
  mixins: [permissionMixins],
  data() {
    return {
      tablePage: {
        page: 1,
        size: 5
      },
      total: 0,
      employees: [],
      showDialog: false,
      visibleQRCode: false, // 显示二维码弹出层
      setRoleDialog: false,
      employeesId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    async loadEmployees() {
      const res = await getEmployeesList(this.tablePage)
      this.total = res.total
      this.employees = res.rows
    },
    handleCurrentChange(val) {
      this.tablePage.page = val
      this.loadEmployees()
    },
    onClickDel(row) {
      this.$confirm('确认删除？')
        .then(async _ => {
          await delEmployee(row.id)
          this.$message.success('删除成功！')
          this.loadEmployees()
        })
        .catch(_ => {})
    },
    onExcelExport() {
      // 懒加载文件 返回一个promise
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows: res } = await getEmployeesList({
          page: 1,
          size: this.total
        })
        const mapKey = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        const data = this.forMatExcelData(res, mapKey)
        excel.export_json_to_excel({
          header: Object.keys(mapKey), // 表头 必填
          data, // 具体数据 必填
          filename: '🐂🐎', // 非必填 文件名
          autoWidth: true, // 非必填 宽带自适应
          bookType: 'xlsx' // 非必填 后缀
        })
      })
    },
    forMatExcelData(res, mapKey) {
      // 将数据格式转为excel所需要的格式
      return res.map(item =>
        Object.keys(mapKey).map(hitem => {
          if (
            item[mapKey[hitem]] - 0 > 0 &&
            (hitem === '入职日期' || hitem === '转正日期')
          ) {
            return formatDate_day(item[mapKey[hitem]], '/')
          } else if (hitem === '聘用形式') {
            return formatHireType(item[mapKey[hitem]])
          }
          return item[mapKey[hitem]]
        })
      )
    },
    onClickAvatar(imgURL) {
      if (!imgURL) return
      this.visibleQRCode = true
      this.$nextTick(() => {
        const canvas = document.querySelector('#qrcode')
        QRCode.toCanvas(canvas, imgURL, function(err) {
          if (err) return this.$message.error('生成失败！')
        })
      })
    },
    onClickRole(id) {
      this.setRoleDialog = true
      this.employeesId = id
    }
  }
}
</script>

<style scoped lang="scss">
.staffPhoto {
  width: 50px;
  height: 50px;
}
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  text-align: center;
  .el-dialog__headerbtn {
    top: 8px;
    right: 8px;
  }
}
</style>
